<template>
	<div class="billing-report">
		<div style="display: flex; justify-content: space-between">
			<div style="display: flex">
				<el-date-picker v-model="selectDate" :clearable="false" type="month" placeholder="选择日期"
					@change="changeDate">
				</el-date-picker>
				<el-button type="primary" @click="exportExcel" style="margin-left: 10px;" v-debounce>
					导出账单
				</el-button>
			</div>
			<div style="display: flex">
				<el-select v-model="select" style="width: 200px;" @change="getTableData">
					<el-option label="不排序" :value="void 0"></el-option>
					<el-option label="优先按月销量降序" :value="1"></el-option>
					<el-option label="优先按月销量升序" :value="2"></el-option>
					<el-option label="优先按年销量降序" :value="3"></el-option>
					<el-option label="优先按年销量升序" :value="4"></el-option>
				</el-select>
				<el-input style="width: 250px" v-model="partName" placeholder="按产品名称或型号搜索" @change="getTableData"
					clearable>
				</el-input>
				<el-select v-model="warehouseType" style="width: 200px;" @change="getTableData">
					<el-option v-for="item in productlibraryList" :label="item.libraryName" :value="item.id"
						:key="item.id"></el-option>
				</el-select>
				<el-select v-model="isProduct" style="width: 200px;" @change="getTableData">
					<el-option v-for="item in typeListComputed" :label="item.productType" :value="item.id"
						:key="item.id"></el-option>
				</el-select>
				<el-button style="margin-left: 10px" @click="reset" v-debounce>重置</el-button>
			</div>
		</div>

		<div class="goods-table">
			<el-table :data="tableData" v-loading="loading" border stripe style="width: 100%" height="100%">
				<el-table-column prop="i" label="序号" fixed="left" width="50">
				</el-table-column>
				<el-table-column label="产品图片" width="115">
					<template slot-scope="scope">
						<el-image style="width: 90px; height: 90px" :src="READ_IMG_URL + scope.row.image"
							:preview-src-list="new Array(READ_IMG_URL + scope.row.image)" fit="cover">
						</el-image>
					</template>
				</el-table-column>
				<el-table-column prop="warehouseType" label="类型库" width="200">
					<template slot-scope="scope">
						<div>{{ productlibraryList.find(item => item.id == scope.row.warehouseType)?.libraryName ??
							"无类型库"
							}}</div>
					</template>
				</el-table-column>
				<el-table-column prop="isProduct" label="产品类型" width="80">
					<template slot-scope="scope">
						<el-tag>{{ productTypeList.find(item => item.id == scope.row.isProduct)?.productType }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="partName" label="产品名称" width="150">
				</el-table-column>
				<el-table-column prop="model" label="产品型号" width="200">
				</el-table-column>
				<el-table-column prop="salesQuantity" label="月销售量" width="80">
				</el-table-column>
				<el-table-column prop="nsalesQuantity" label="年销售量" width="80">
				</el-table-column>
				<el-table-column prop="grossProfit" label="毛利润" width="70">
				</el-table-column>
				<el-table-column prop="netProfit" label="净利润" width="70">
				</el-table-column>
				<el-table-column prop="cost" label="成本费/采购单价" width="80">
				</el-table-column>
				<el-table-column prop="price" label="销售单价" width="80">
				</el-table-column>
				<el-table-column prop="process" label="加工费" width="70">
				</el-table-column>
				<el-table-column prop="labour" label="人工费" width="70">
				</el-table-column>
				<el-table-column prop="packing" label="打包费" width="70">
				</el-table-column>
				<el-table-column prop="freight" label="运输费" width="70">
				</el-table-column>
				<el-table-column prop="siteFee" label="场地费" width="70">
				</el-table-column>
				<el-table-column prop="isIncludeTax" label="是否含税" width="80">
					<template slot-scope="scope">
						<el-tag size="medium" v-if="scope.row.isIncludeTax === 0">
							含税
						</el-tag>
						<el-tag v-if="scope.row.isIncludeTax === 1" size="medium" color="#F67A7A" style="color: white">
							不含税
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="devicesDescribe" label="产品描述" width="200">
				</el-table-column>
				<el-table-column prop="remark" label="备注" width="200">
				</el-table-column>
				<el-table-column label="操作" fixed="right" width="80">
					<template slot-scope="scope">
						<el-button type="text" @click="expenseDialog(scope.row)">
							修改费用
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination background :current-page="currentPage" :page-size="pageSize" :total="total"
				:page-sizes="[20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
				@size-change="handleSizeChange" @current-change="handleCurrentChange">
			</el-pagination>
		</div>
		<!-- 产品费用信息 -->
		<el-dialog :visible.sync="expenseDialogShow" width="75%" :title="title" @close="expenseDialogClose">
			<el-form inline label-position="top" :model="devices">
				<el-form-item label="产品类型">
					<el-select v-model="devices.isProduct" disabled style="width: 100%;">
						<el-option label="零件" :value="1"></el-option>
						<el-option label="成品" :value="0"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="产品名称" prop="partName">
					<el-input :value="devices.partName" placeholder="产品名称" readonly>
					</el-input>
				</el-form-item>
				<el-form-item label="产品型号" prop="model">
					<el-input :value="devices.model" placeholder="产品型号" readonly>
					</el-input>
				</el-form-item>
				<el-form-item label="成本费/采购单价">
					<el-input v-model="devices.cost" type="number" placeholder="成本费/采购单价" step="0.01"
						@input="checkPrice($event, 'cost')">
					</el-input>
				</el-form-item>
				<el-form-item label="加工费">
					<el-input v-model="devices.process" type="number" placeholder="加工费" step="0.01"
						@input="checkPrice($event, 'process')">
					</el-input>
				</el-form-item>
				<el-form-item label="人工费">
					<el-input v-model="devices.labour" type="number" placeholder="人工费" step="0.01"
						@input="checkPrice($event, 'labour')">
					</el-input>
				</el-form-item>
				<el-form-item label="打包费">
					<el-input v-model="devices.packing" type="number" placeholder="打包费" step="0.01"
						@input="checkPrice($event, 'packing')">
					</el-input>
				</el-form-item>
				<el-form-item label="运输费">
					<el-input v-model="devices.freight" type="number" placeholder="运费" step="0.01"
						@input="checkPrice($event, 'freight')">
					</el-input>
				</el-form-item>
				<el-form-item label="场地费">
					<el-input v-model="devices.siteFee" type="number" placeholder="场地费" step="0.01"
						@input="checkPrice($event, 'siteFee')">
					</el-input>
				</el-form-item>
				<el-form-item label="销售单价">
					<el-input v-model="devices.price" type="number" placeholder="销售单价" step="0.01"
						@input="checkPrice($event, 'price')">
					</el-input>
				</el-form-item>
				<el-form-item label="是否含税">
					<el-select v-model="devices.isIncludeTax" style="width: 100%;">
						<el-option label="不含税" :value="1"></el-option>
						<el-option label="含税" :value="0"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="产品描述">
					<el-input :value="devices.devicesDescribe" placeholder="产品描述" type="textarea"
						:autosize="{ minRows: 4, maxRows: 6 }" readonly>
					</el-input>
				</el-form-item>
				<el-form-item label="备注">
					<el-input v-model="devices.remark" placeholder="备注" type="textarea"
						:autosize="{ minRows: 4, maxRows: 6 }">
					</el-input>
				</el-form-item>
				<el-form-item label="图片">
					<img :src="READ_IMG_URL + devices.image" class="htimg" />
				</el-form-item>
			</el-form>
			<div>
				<el-button @click="expenseDialogShow = false">取消</el-button>
				<el-button type="primary" @click="onSubmit" v-debounce>修改</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import warehouseApi from '../../api/warehouse';
import financeApi from '../../api/financeManage';
import config from '../../api/apiURL.js';
import productType from '../../api/productType.js';
import productlibrary from '../../api/productlibrary.js';
export default {
	data() {
		return {
			READ_IMG_URL: config.READ_IMG_URL,
			loading: false,
			tableData: [],
			currentPage: 1,
			pageSize: 50,
			total: 0,
			selectDate: null,
			yearMonth: null,
			select: 1,
			partName: null,
			isProduct: null,
			warehouseType: void 0,
			expenseDialogShow: false,
			devices: {
				id: null,
				isProduct: 1, // 0成品，1零件
				partName: null, // 产品名称
				model: null, // 产品型号
				count: 0, // 库存数量
				cost: 0.00, // 成本费/采购单价
				process: 0.00, // 加工费
				labour: 0.00, // 人工费
				packing: 0.00, // 打包费
				freight: 0.00, // 运费
				siteFee: 0.00, // 场地费
				price: 0.00, // 销售单价
				isIncludeTax: 1, // 是否含税，0含税，1不含税
				image: null, // 产品图片
				devicesDescribe: null, // 产品描述
				remark: null, // 备注
				productPartList: [], //零件列表
				isUpdatePartList: 0, // 0不修改成品零件列表，1修改成品零件列表
			},
			title: "",
			productTypeList: new Array(),
			productlibraryList: new Array()
		}
	},
	mounted() {
		this.initializeDate();
		this.getTableData();
		this.getProductTypeList()
		this.getProductlibraryList()
	},
	computed: {
		typeListComputed() {
			return this.warehouseType ?
				this.productTypeList.filter(
					value => this.productlibraryList.find(
						i => i.id == this.warehouseType
					).producttype.split(',').findIndex(item => item == value.id) != -1
				) : this.productTypeList
		}
	},
	methods: {
		// 初始化日期
		initializeDate() {
			const currentYear = new Date().getFullYear();
			let currentMonth = new Date().getMonth() + 1;
			let currentDay = new Date().getDate();
			currentMonth = currentMonth < 10 ? '0' + currentMonth : currentMonth;
			currentDay = currentDay < 10 ? '0' + currentDay : currentDay;
			this.yearMonth = `${currentYear}-${currentMonth}`;
			this.selectDate = this.yearMonth;
		},
		// 获取表格数据
		getTableData() {
			const data = {
				select: this.select,
				partName: this.partName,
				isProduct: this.isProduct,
				warehouseType: this.warehouseType,
				yearMonth: this.yearMonth,
				currentPage: this.currentPage,
				pageSize: this.pageSize,
			}
			this.loading = true;
			financeApi.calculatingProfit(data).then(res => {
				if (res.code === 200) {
					this.total = res.data.total
					this.tableData = res.data.devicesVoList.map((item, index) => {
						item.i = (this.currentPage - 1) * this.pageSize + index + 1;
						return item;
					})
				}
			}).finally(() => {
				this.loading = false;
			})
		},
		// 
		changeIsProduct() {
			this.currentPage = 1;
			this.getTableData();
		},
		// 页码变化
		handleCurrentChange(curPage) {
			this.currentPage = curPage;
			this.getTableData();
		},
		// 页码条数变化
		handleSizeChange(pageSize) {
			this.pageSize = pageSize;
			this.getTableData();
		},
		// 日期改变
		changeDate() {
			//console.log("选择的日期==>",this.selectDate)
			if (this.selectDate !== null) {
				let year = this.selectDate.getFullYear();
				let month = this.selectDate.getMonth() + 1; // 月份从 0 开始，需要加 1
				let day = this.selectDate.getDate();
				// 格式化月份和日期，确保始终是两位数
				const formattedMonth = month < 10 ? '0' + month : month;
				const formattedDay = day < 10 ? '0' + day : day;
				// 拼接字符串
				this.yearMonth = `${year}-${formattedMonth}`;
				this.selectDate = this.yearMonth;
				this.getTableData()
			}
		},
		// 重置
		reset() {
			this.selectDate = new Date;
			this.yearMonth = null;
			this.partName = null;
			this.isProduct = null;
			this.changeDate();
		},
		// 修改费用弹窗
		expenseDialog(row) {
			const loading = this.$loading({
				lock: true,
				text: 'Loading',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			warehouseApi.getDevice(row).then(res => {
				if (res.code === 200) {
					this.devices = res.data
					this.title = this.devices.partName;
					this.expenseDialogShow = true;
				}
			}).finally(() => {
				loading.close();
			})
		},
		// 修改费用弹窗关闭
		expenseDialogClose() {
			this.devices = {}
			this.title = "";
		},
		// 检查数字，小于0.00，或者超过小数点后两位返回0
		checkNumber(value) {
			if (value < 0.00) {
				value = 0;
			}
			// 使用正则表达式匹配小数点后两位以内的数字或整数
			let regex = /^\d+(\.\d{1,2})?$/;
			if (!regex.test(value)) {
				value = 0
			}
			return value;
		},
		// 检查输入的金额
		checkPrice(e, type) {
			let inputNumber = parseFloat(this.devices[type]);
			inputNumber = this.checkNumber(inputNumber);
			this.devices[type] = inputNumber
		},
		// 提交
		onSubmit() {
			this.$confirm('是否要修改？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				const loading = this.$loading({
					lock: true,
					text: 'Loading',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				this.devices.isUpdatePartList = 0;
				// 修改
				warehouseApi.updateDevice(this.devices).then(res => {
					if (res.code === 200) {
						this.$message.success("修改成功");
						this.expenseDialogShow = false;
						this.getTableData();
					}
				}).finally(() => {
					loading.close();
				})
			}).catch(() => {
				// 用户点击了取消按钮的处理逻辑
			});
		},
		//导出Excel
		exportExcel() {
			const data = this.formatData(this.tableData); // 将数据格式化为xlsx可以识别的格式
			const wb = this.$XLSX.utils.book_new();
			const ws = this.$XLSX.utils.json_to_sheet(data);
			// 设置列宽
			const columnWidths = [{
				wch: 5
			}, // 序号
			{
				wch: 8
			}, // 产品类型
			{
				wch: 20
			}, // 产品名称
			{
				wch: 35
			}, // 产品型号
			{
				wch: 8
			}, // 月销售量
			{
				wch: 8
			}, // 毛利润
			{
				wch: 8
			}, // 净利润
			{
				wch: 8
			}, // 成本费/采购单价
			{
				wch: 8
			}, // 销售单价
			{
				wch: 8
			}, // 加工费
			{
				wch: 8
			}, // 人工费
			{
				wch: 8
			}, // 打包费
			{
				wch: 8
			}, // 运输费费
			{
				wch: 8
			}, // 场地费
			{
				wch: 8
			}, // 是否含税
			{
				wch: 25
			}, // 产品描述
			{
				wch: 25
			} // 备注列宽度
			];
			ws['!cols'] = columnWidths;
			this.$XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
			let fileName = this.yearMonth + "利润报表"
			this.$XLSX.writeFile(wb, fileName + ".xlsx");
		},
		formatData(data) {
			// 格式化表格数据，将对象数组转换为数组对象
			return data.map((item) => {
				item.product = this.productTypeList.find(value => value.id == item.isProduct)?.productType
				// if (item.isProduct === 0) {
				// 	item.product = "成品"
				// } else if (item.isProduct === 1) {
				// 	item.product = "零件"
				// }
				item.warehouseType = this.productlibraryList.find(value => value.id == item.warehouseType)?.libraryName
				if (item.isIncludeTax === 0) {
					item.includeTax = "含税"
				} else if (item.isIncludeTax === 1) {
					item.includeTax = "不含税"
				}
				const {
					i,
					product, // 0成品，1零件
					warehouseType,
					partName, // 产品名称
					model, // 产品型号
					salesQuantity, // 月销售量
					cost, // 成本费/采购单价
					process, // 加工费
					labour, // 人工费
					packing, // 打包费
					freight, // 运费
					siteFee, // 场地费
					price, // 销售单价
					includeTax, // 是否含税，0含税，1不含税
					devicesDescribe, // 产品描述
					remark, // 备注
					grossProfit,
					netProfit
				} = item;
				return {
					序号: i,
					产品类型: product,
					产品类型库: warehouseType,
					产品名称: partName,
					产品型号: model,
					月销售量: salesQuantity,
					毛利润: grossProfit,
					净利润: netProfit,
					成本费采购单价: cost,
					销售单价: price,
					加工费: process,
					人工费: labour,
					打包费: packing,
					运输费: freight,
					场地费: siteFee,
					是否含税: includeTax,
					产品描述: devicesDescribe,
					备注: remark
				};
			});
		},
		async getProductTypeList() {
			let res = await productType.getProductType()
			res.data.map(item => {
				item.relevance = (item.relevance == "ALL" || item.relevance == "VOID") ? item.relevance : item.relevance.split(",").map(Number)
			})
			this.productTypeList = res.data
		},
		async getProductlibraryList() {
			let res = await productlibrary.getProductlibrary()
			this.productlibraryList = res.data
		}
	}
}
</script>

<style scoped>
.billing-report {
	height: 100%;
}

.goods-table {
	height: 94%;
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	justify-content: center;
	margin-top: 10px;
}

.htimg {
	width: 150px;
	height: 150px;
	object-fit: cover;
	/* 保持原始宽高比，填充容器 */
}

.el-form-item {
	width: 450px;
	margin-left: 10px;
}
</style>